package org.maylove.wuziqi.controller;

import org.maylove.wuziqi.common.ResposeMessage;
import org.maylove.wuziqi.pojo.history.History;
import org.maylove.wuziqi.pojo.user.dto.*;
import org.maylove.wuziqi.common.RedisUtil;
import org.maylove.wuziqi.common.TokenGenerator;
import org.maylove.wuziqi.service.HistoryService;
import org.maylove.wuziqi.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RedisUtil redisUtil;

    Logger logger = LoggerFactory.getLogger(getClass());

    //  注册
    @PostMapping(value = "/register")
    @ResponseBody
    public ResposeMessage register(@RequestBody UserRegisterDto userRegisterDto) {
        String data = userService.register(userRegisterDto);
        return ResposeMessage.success(data, null);
    }

    //  登录
    @PostMapping(value = "/login")
    @ResponseBody
    public ResposeMessage<UserDto> login(@RequestBody UserLoginDto userLoginDto) {
        Object data = userService.login(userLoginDto);
        if(data == "Username does not exist!" || data == "Wrong password!") {
            return ResposeMessage.success((String)data, null);
        }
        String token = TokenGenerator.generateToken();
        ((UserDto)data).setToken(token);
        redisUtil.set(((UserDto)data).getUserId().toString(), token);
        redisUtil.set(token + "_userId", ((UserDto)data).getUserId());
        logger.info("Player login successful! userid:{}", ((UserDto)data).getUserId());
        return ResposeMessage.success("success", (UserDto)data);
    }

    //  修改昵称
    @PostMapping(value = "/changeNickname")
    @ResponseBody
    public ResposeMessage changeNickname(@RequestHeader("token") String token, @RequestBody UserChangeNickNameDto userChangeNickNameDto) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }

        String data = userService.changeNicknam((Long)redisUtil.get(token + "_userId"), userChangeNickNameDto);
        if(Objects.equals(data, "User has changed!")) {
            logger.info("Player change nickname successful! userid:{}", ((Long) redisUtil.get(token + "_userId")));
            if (redisUtil.exists("nickname_" + ((Long) redisUtil.get(token + "_userId")).toString()))
                redisUtil.delete("nickname_" + ((Long) redisUtil.get(token + "_userId")).toString());
        }
        return ResposeMessage.success(data, null);
    }

    //  修改密码
    @PostMapping(value = "/changePassword")
    @ResponseBody
    public ResposeMessage changePassword(@RequestHeader("token") String token, @RequestBody UserChangePasswordDto userChangePasswordDto) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }

        String data = userService.changePassword((Long)redisUtil.get(token + "_userId"), userChangePasswordDto);
        if(Objects.equals(data, "User has changed!")) logger.info("Player change pwd successful! userid:{}", ((Long) redisUtil.get(token + "_userId")));
        return ResposeMessage.success(data, null);
    }

    //  查询用户信息
    @PostMapping(value = "/myInfo")
    @ResponseBody
    public ResposeMessage<UserDto> getUserInfo(@RequestHeader("token") String token) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }

        UserDto userDto = userService.getUserInfo((Long)redisUtil.get(token + "_userId"));
        if(userDto == null) return ResposeMessage.success("User not logged in!", null);
        return ResposeMessage.success("success", userDto);
    }

    //  创建房间
    @PostMapping(value = "/createRoom")
    @ResponseBody
    public ResposeMessage<Integer> createRoom(@RequestHeader("token") String token) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }

        Integer data = userService.createRoom((Long)redisUtil.get(token + "_userId"));
        if(data == -1) return ResposeMessage.success("The room is full!", null);
        else {
            redisUtil.set(token + "_roomId", data);
            logger.info("Player id:{} create room id:{} successful!", ((Long) redisUtil.get(token + "_userId")), data);
            return ResposeMessage.success("success", data);
        }
    }

    //  加入房间
    @PostMapping("/joinRoom")
    @ResponseBody
    public ResposeMessage<Integer> joinRoom(@RequestHeader("token") String token, @RequestBody int roomId) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }

        Integer data = userService.joinRoom((Long)redisUtil.get(token + "_userId"), roomId);
        if(data == -1) return ResposeMessage.success("The room does not exist!", null);
        else if(data == -2) return ResposeMessage.success("The room is already full!", null);
        else if(data == -3) return ResposeMessage.success("Cannot join the room created by oneself!", null);
        else {
            redisUtil.set(token + "_roomId", roomId);
            logger.info("Player id:{} join room id:{} successful!", ((Long) redisUtil.get(token + "_userId")), roomId);
            return ResposeMessage.success("success", roomId);
        }
    }

    //  获取昵称
    @PostMapping("/getNickName")
    @ResponseBody
    public ResposeMessage<String> getNickName(@RequestHeader("token") String token, @RequestBody Long userId) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }

        logger.info("Player id:{} get nickname id:{} successful!", ((Long) redisUtil.get(token + "_userId")), userId);
        if(redisUtil.exists("nickname_" + userId.toString())) {
            return ResposeMessage.success("success", (String)redisUtil.get("nickname_" + userId.toString()));
        }
        String nickname = userService.getNickname(userId);
        redisUtil.set("nickname_" + userId.toString(), nickname);
        return ResposeMessage.success("success", nickname);
    }

    //  获取历史记录
    @PostMapping("/getHistory")
    @ResponseBody
    public ResposeMessage<List<History> > getHistory(@RequestHeader("token") String token) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }
        logger.info("Player id:{} get history successful!", ((Long) redisUtil.get(token + "_userId")));
        return ResposeMessage.success("success", historyService.getHistory((Long)redisUtil.get(token + "_userId")));
    }

    //  修改用户权限
    @PostMapping("/changeIdentity")
    @ResponseBody
    public ResposeMessage changeIdentity(@RequestHeader("token") String token, @RequestBody UserChangeIdentityDto userChangeIdentityDto) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }

        //  判权
        int identity = userService.getIdentity((Long)redisUtil.get(token + "_userId"));
        if(identity<2 || (identity==2 && userChangeIdentityDto.getIdentity()>1) || (identity==3 && userChangeIdentityDto.getIdentity()>2)) {
            return ResposeMessage.success("Insufficient user permissions!", null);
        }

        logger.info("Player id:{} change identity id:{} to {} successful!", ((Long) redisUtil.get(token + "_userId")), userChangeIdentityDto.getUserId(), userChangeIdentityDto.getIdentity());
        userService.changeIdentity(userChangeIdentityDto);
        return ResposeMessage.success("success", null);
    }

    //  获取用户权限
    @PostMapping("/getIdentity")
    @ResponseBody
    public ResposeMessage<Integer> getIdentity(@RequestHeader("token") String token) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }

        logger.info("Player id:{} get identity successful!", ((Long) redisUtil.get(token + "_userId")));
        return ResposeMessage.success("success", userService.getIdentity((Long)redisUtil.get(token + "_userId")));
    }

    //  获取用户
    @PostMapping("/getUser")
    @ResponseBody
    public ResposeMessage<List<UserGetDto>> getUser(@RequestHeader("token") String token, @RequestBody UserPageDto userPageDto) {
        //  查找一下用户是否处于登录态
        if(token.isEmpty() || !redisUtil.exists(token + "_userId") || redisUtil.get(token + "_userId") == null || !redisUtil.get(redisUtil.get(token + "_userId").toString()).equals(token)) {
            return ResposeMessage.success("User not logged in!", null);
        }

        //  判权
        if(userService.getIdentity((Long)redisUtil.get(token + "_userId")) < 2) {
            return ResposeMessage.success("Insufficient user permissions!", null);
        }


        logger.info("Player id:{} get user list successful!", ((Long) redisUtil.get(token + "_userId")));
        return ResposeMessage.success("success", userService.getUser(userPageDto));
    }
}
